package com.guqiao.library.exception

import com.google.gson.JsonParseException
import com.google.gson.JsonSyntaxException
import org.json.JSONException
import retrofit2.HttpException
import java.io.IOException
import java.io.NotSerializableException
import java.net.UnknownHostException
import java.text.ParseException
import javax.net.ssl.SSLHandshakeException

/**
 *
 * @author jiangyao
 * @date 2019-07-19 09:39
 * @des
 */

class ApiException(throwable: Throwable, code: Int, msg: String?) : Exception(throwable) {

    companion object {
        fun handleException(e: Throwable) {
            when {
                e is HttpException -> ApiException(e, e.code(), e.response().errorBody()?.string())
                e is IOException -> ApiException(e, IO_ERROR, "IO异常")
                e is UnknownHostException -> ApiException(e, UNKNOWN_HOST_ERROR, "未知主机")
                e is NullPointerException -> ApiException(e, NULL_POINTER_ERROR, "空指针异常")
                e is SSLHandshakeException -> ApiException(e, SSL_ERROR, "SSL错误")
                e is ClassCastException -> ApiException(e, CLASS_CAST_ERROR, "类型转换错误")
                e is ClassNotFoundException -> ApiException(e, CLASS_NOT_FOUND_ERROR, e.message)
                e is JsonParseException || e is JSONException
                        || e is JsonSyntaxException || e is NotSerializableException ||
                        e is ParseException -> ApiException(e, PARSE_ERROR, "解析错误")
                e is RuntimeException -> ApiException(e, RUNTIME_ERROR, e.message)
                else -> ApiException(e, UNKNOWN_ERROR, e.message)
            }
        }

        /**
         * 未知错误
         */
        private const val UNKNOWN_ERROR = 0x01
        /**
         * IO 错误
         */
        private const val IO_ERROR = 0x02
        /**
         * 未知主机错误
         */
        private const val UNKNOWN_HOST_ERROR = 0x03
        /**
         * 空指针异常
         */
        private const val NULL_POINTER_ERROR = 0x04
        /**
         * SSL错误
         */
        private const val SSL_ERROR = 0x05
        /**
         * 类型转换错误
         */
        private const val CLASS_CAST_ERROR = 0x06
        /**
         * 解析错误
         */
        private const val PARSE_ERROR = 0x07
        /**
         * 运行时错误
         */
        private const val RUNTIME_ERROR = 0x08
        /**
         * 类找不到
         */
        private const val CLASS_NOT_FOUND_ERROR = 0x09
    }
}